package com.punai.web.controller.cs;

import com.google.protobuf.ServiceException;
import com.punai.common.annotation.Log;
import com.punai.common.core.controller.BaseController;
import com.punai.common.core.domain.AjaxResult;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.enums.BusinessType;
import com.punai.system.bo.cs.EpPermissionBo;
import com.punai.system.domain.CsRole;
import com.punai.system.service.CsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/cs/role")
public class CsRoleController extends BaseController {

    @Autowired
    private CsRoleService csRoleService;
    @PreAuthorize("@ss.hasPermi('cs:role:list')")
    @GetMapping("/list")
    public TableDataInfo list(CsRole role)
    {
        startPage();
        Long companyId = getCompanyId();
        role.setCompanyId(companyId);
        List<CsRole> list = csRoleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('cs:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CsRole role) throws ServiceException {
        role.setCompanyId(getCompanyId());
        if (csRoleService.checkRoleNameUnique(role))
        {
            return AjaxResult.error("新增角色'" + role.getName() + "'失败，角色名称已存在");
        }
        return toAjax(csRoleService.insertRole(role));
    }

    @PreAuthorize("@ss.hasPermi('cs:role:list')")
    @GetMapping("{id}")
    public AjaxResult getInfo(@PathVariable String id) throws ServiceException {
        return AjaxResult.success(csRoleService.getCsRole(id,getCompanyId()));
    }


    @PreAuthorize("@ss.hasPermi('cs:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult update(@RequestBody CsRole role) throws ServiceException {
        role.setCompanyId(getCompanyId());
        return toAjax(csRoleService.updateRole(role));
    }

    @PreAuthorize("@ss.hasPermi('cs:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult delete(@PathVariable Long[] roleIds) throws ServiceException {
        return toAjax(csRoleService.deleteRole(roleIds,getCompanyId()));
    }


    @PreAuthorize("@ss.hasPermi('cs:role:list')")
    @GetMapping("getEpAndSelfPermission")
    public AjaxResult getEpPermission(CsRole role)
    {
        Long companyId = getCompanyId();
        role.setCompanyId(companyId);
        // 树结构 选择的项
        EpPermissionBo epPermissionBo = csRoleService.getEpPermission(role);
        return AjaxResult.success(epPermissionBo);
    }

}
